package com.vcredit.creditcat.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.vcredit.creditcat.model.UserRole;
import com.vcredit.creditcat.persistence.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.vcredit.creditcat.framework.pagination.DefaultCriteria;
import com.vcredit.creditcat.framework.pagination.Page;
import com.vcredit.creditcat.framework.util.MD5Encoder;
import com.vcredit.creditcat.model.Resource;
import com.vcredit.creditcat.model.User;
import com.vcredit.creditcat.persistence.ResourceMapper;
import com.vcredit.creditcat.persistence.UserMapper;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ResourceMapper resourceMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;

	public User findById(Long id){
		return userMapper.findById(id);
	}
	public Page<User> findByPage(DefaultCriteria criteria){
		long count=userMapper.findByPageCount(criteria);
		List<User> userList=userMapper.findByPage(criteria);
		return new Page<User>(count, userList);
	}
	
	public void insert(User user){
		userMapper.insert(user);
	}
	public void update(User user){
		userMapper.update(user);
	}
	public void delete(long id){
		userMapper.delete(id);
	}
	public void insertUserRole(UserRole userRole){userRoleMapper.insert(userRole);}
	
	public boolean login(String userName, String password) {
		
		List<User> users = userMapper.find(new User(userName));
		if (users.size() == 1) {
			if (users.get(0).getPassword().equals(MD5Encoder.encode(password)))
				return true;
		}
		return false;
	}
	public List<Resource> findMenu(Long userId) {
		
		List<Resource> menus = resourceMapper.findByUserId(userId,0);
		List<Resource> baseMenus=new ArrayList<>();
		for(Resource menu:menus){
			if(menu.getpId()==0){
				baseMenus.add(menu);
			}
		}
		Iterator<Resource> iterator=baseMenus.iterator();
		while(iterator.hasNext()){
			Resource baseMenu=iterator.next();
			List<Resource> childMenus=new ArrayList<>();
			for(Resource menu:menus){
				if(menu.getpId()==baseMenu.getId()){
					childMenus.add(menu);
				}
			}
			baseMenu.setResources(childMenus);
			if(baseMenu.getResources().size()==0){
				iterator.remove();
			}
		}
		return baseMenus;
	}
}
